package com.wstuo.itsm.cim.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.attachment.dao.IAttachmentDAO;
import com.wstuo.common.config.attachment.entity.Attachment;
import com.wstuo.common.config.attachment.service.IAttachmentService;
import com.wstuo.common.config.category.dao.ICICategoryDAO;
import com.wstuo.common.config.category.dao.IEventCategoryDAO;
import com.wstuo.common.config.category.dto.EventCategoryDTO;
import com.wstuo.common.config.category.entity.CICategory;
import com.wstuo.common.config.category.entity.EventCategory;
import com.wstuo.common.config.category.service.IEventCategoryService;
import com.wstuo.common.config.customfilter.dto.KeyTransferDTO;
import com.wstuo.common.config.customfilter.service.IFilterService;
import com.wstuo.common.config.customfilter.service.ILinksEventQueryServices;
import com.wstuo.common.config.dictionary.dao.IDataDictionaryGroupDAO;
import com.wstuo.common.config.dictionary.dao.IDataDictionaryItemsDAO;
import com.wstuo.common.config.dictionary.entity.DataDictionaryItems;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.exportmq.ExportMessageProducer;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.file.csv.CSVWriter;
import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.service.IUserInfoService;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.security.utils.FileEncodeUtils;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.tools.dao.IExportInfoDAO;
import com.wstuo.common.tools.dto.ExportPageDTO;
import com.wstuo.common.tools.dto.ExportQueryDTO;
import com.wstuo.common.tools.dto.StatResultDTO;
import com.wstuo.common.tools.entity.ExportInfo;
import com.wstuo.common.tools.service.IExportInfoService;
import com.wstuo.common.tools.util.Base64;
import com.wstuo.common.util.DepreciationUtil;
import com.wstuo.common.util.MathUtils;
import com.wstuo.common.util.StringUtils;
import com.wstuo.common.util.TimeUtils;
import com.wstuo.itsm.bean.IBeanUtil;
import com.wstuo.itsm.cim.dao.IBehaviorModificationDAO;
import com.wstuo.itsm.cim.dao.ICIDAO;
import com.wstuo.itsm.cim.dao.ICIHistoryUpdateDAO;
import com.wstuo.itsm.cim.dto.BehaviorModificationDTO;
import com.wstuo.itsm.cim.dto.CIDTO;
import com.wstuo.itsm.cim.dto.CIDetailDTO;
import com.wstuo.itsm.cim.dto.CIGridDTO;
import com.wstuo.itsm.cim.dto.CIHistoryUpdateDTO;
import com.wstuo.itsm.cim.dto.CIQueryDTO;
import com.wstuo.itsm.cim.dto.CIScanDTO;
import com.wstuo.itsm.cim.dto.CIUpdateDTO;
import com.wstuo.itsm.cim.dto.CiHardwareDTO;
import com.wstuo.itsm.cim.dto.CiSoftwareDTO;
import com.wstuo.itsm.cim.dto.HardwareDTO;
import com.wstuo.itsm.cim.dto.HardwareSimpleDTO;
import com.wstuo.itsm.cim.entity.BehaviorModification;
import com.wstuo.itsm.cim.entity.CIHistoryUpdate;
import com.wstuo.itsm.cim.util.CIImportUtil;
import com.wstuo.itsm.cim.entity.CI;
import com.wstuo.itsm.domain.util.ModuleUtils;
import com.wstuo.itsm.itsop.itsopuser.dto.CustomerDataCountDTO;
import com.wstuo.itsm.itsop.itsopuser.service.IITSOPUserService;

/***
 * 配置项Service类
 * 
 * @author QXY
 */
public class CIService implements ICIService {

	final static Logger LOGGER = Logger.getLogger(CIService.class);
	
	@Autowired
	private ICIDAO ciDAO;
	@Autowired
	private IDataDictionaryItemsDAO dataDictionaryItemsDAO;
	@Autowired
	private IDataDictionaryGroupDAO dataDictionaryGroupDAO;
	@Autowired
	private ICICategoryDAO cicategoryDAO;
	@Autowired
	private IAttachmentDAO attachmentDAO;
	@Autowired
	private IAttachmentService attachmentService;
	@Autowired
	private IOrganizationDAO organizationDAO;
	@Autowired
	private IITSOPUserService itsopUserService;
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IFilterService filterService;
	@Autowired
	private ICIHistoryUpdateDAO ciHistoryUpdate;
	@Autowired
	private ExportMessageProducer exportMessageProducer;
	@Autowired
	private IExportInfoDAO exportInfoDAO;
	@Autowired
	private IExportInfoService exportInfoService;
	@Autowired
	private IEventCategoryDAO eventCategoryDAO;
	@Autowired
	private ILinksEventQueryServices linksEventQueryServices;
	@Autowired
	private IOrganizationDAO orgDAO;
	@Autowired
	private AppContext appctx;
	private String product = "";
	@Autowired
	private IEventCategoryService eventCategoryService;
	@Autowired
	private IBeanUtil beanUtil;

	private static String EXPORTPATH = AppConfigUtils.getInstance().getExportPath();
	public static final String MODULECATEGORY = "Location";
	public final static String  CONFIGUREITEMCATEGORY_RES="CONFIGUREITEMCATEGORY_RES";
	@Autowired
	private IBehaviorModificationDAO behaviorModificationDAO;

	/**
	 * 根据CI ID判断是否存在
	 * 
	 * @param ciId
	 *            :查要判断的ID
	 * @return boolean
	 */
	public boolean isConfigureItemExist(Long ciId) {
		boolean bool = false;
		CI ci = ciDAO.findById(ciId);
		if (ci != null) {
			bool = true;
		}
		return bool;
	}

	/**
	 * 根据配置项编号判断是否存在
	 * 
	 * @param ciNo
	 *            :查要判断的ciNo
	 * @return boolean
	 */
	public boolean isConfigureItemExist(String ciNo) {
		boolean result = false;
		CI ci = ciDAO.findUniqueBy("cino", ciNo);
		if (ci != null) {
			result = true;
		}
		return result;
		
	}
	private Long[] categoryAssembly(Long cno){
		Set<Long> longList = new HashSet<Long>();// 唯一集合
		// 查询分类包含的所有子节点
		longList=findCICategorys(cno, longList);
		
		Long[] toArray = longList.toArray(new Long[longList.size()]);
		return toArray;
	}
	/**
	 * 递归查找子节点.
	 */
	private Set<Long> findCICategorys(Long cno, Set<Long> longList) {
		if (cno != null) {
			CICategory ciet = cicategoryDAO.findById(cno);
			List<CICategory> listec=cicategoryDAO.findSubCategoryByPath(ciet.getPath());
			for(CICategory ec:listec){
				longList.add(ec.getCno());
			}
		}
		return longList;
	}

	/**
	 * 配置项分页查询
	 * 
	 * @param ciQueryDTO
	 *            :配置项查询条件属性DTO
	 * @param start
	 *            :第几页
	 * @param limit
	 *            ：每页数
	 * @return PageDTO:分页数据集
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findPagerConfigureItem(CIQueryDTO ciQueryDTO, int start,
			int limit, String sidx, String sord) {
		//防止修改参数越权访问
		String loginName = appctx.getCurrentLoginName();
		if(StringUtils.hasText(loginName)){
			ciQueryDTO.setLoginName(loginName);
		}
		if (ciQueryDTO != null) {
			// 查询分类包含的所有子节点
			if (ciQueryDTO.getCategoryNo() != null) {
				ciQueryDTO.setCategoryNos(categoryAssembly(ciQueryDTO.getCategoryNo()));
			}
			if (ciQueryDTO.getLoginName() != null) {// 获取登录名
				ciQueryDTO.setCategoryRes(userInfoService.findCategoryNosByLoginName(
								ciQueryDTO.getLoginName(),CONFIGUREITEMCATEGORY_RES));// 设置查看权限
			}
			if (ciQueryDTO.getCompanyNos() == null) {
				ciQueryDTO.setCompanyNos(itsopUserService
						.findMyAllCustomer(ciQueryDTO.getLoginName()));
			}
		}
		
		PageDTO page = ciDAO.findPager(ciQueryDTO, start, limit, sidx, sord);
		List<CI> entities = (List<CI>) page.getData();
		List<CIGridDTO> dtos = new ArrayList<CIGridDTO>();
		for (CI entity : entities) {
			CIGridDTO dto = new CIGridDTO();
			entity2dto(entity, dto);
			dtos.add(dto);
		}
		page.setData(dtos);
		return page;
	}

	/**
	 * 自定义分页查询配置项列表.
	 * 
	 * @return String
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findConfigureItemPagerByCustomtFilter(CIQueryDTO ciQueryDTO,
			int start, int limit, String sidx, String sord) {
		if (ciQueryDTO.getLoginName() != null) {// 获取登录名
			ciQueryDTO.setCategoryRes(userInfoService.findCategoryNosByLoginName(
					ciQueryDTO.getLoginName(), CONFIGUREITEMCATEGORY_RES));// 设置查看权限
		}
		PageDTO pageDTO = filterService.findPageByFilter(
				ciQueryDTO.getFilterId(), start, limit, sidx, sord);
		List<CI> entities = (List<CI>) pageDTO.getData();
		List<CIGridDTO> dtos = new ArrayList<CIGridDTO>(entities.size());
		for (CI entity : entities) {
			CIGridDTO dto = new CIGridDTO();
			entity2dto(entity, dto);
			dtos.add(dto);
		}
		pageDTO.setData(dtos);
		return pageDTO;
	}

	/**
	 * 根据ID查询配置项
	 * 
	 * @param ciId
	 *            配置项ID
	 * @return CIDTO
	 */
	@Transactional
	public CIDetailDTO findConfigureItemById(Long ciId) {
		CI entity = ciDAO.findById(ciId);
		CIDetailDTO dto = new CIDetailDTO();
		try {
			if (entity != null) {
				List<Attachment> attrs = entity.getCiAttachements();
				if (attrs != null && attrs.size() > 0&& entity.getCiAttachements() != null)
					dto.setAttachments(attrs);
				entity2dto(entity, dto);
			}
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return dto;
	}

	/**
	 * 配置项批量删除
	 * 
	 * @param ciIds
	 *            要删除的配置项ID数组
	 * @return boolean
	 */
	@Transactional
	public boolean deleteConfigureItem(Long[] ciIds) {
		boolean bool = true;
		ciDAO.deleteByIds(ciIds);
		return bool;
	}
	/**
	 * 获取相关附件
	 * @param aids
	 * @param attachmentStr
	 * @param attrType
	 * @return List<Attachment>
	 */
	private List<Attachment> getReleatedAttachment(Long[] aids,String attachmentStr,String attrType){
		List<Attachment> attrs = attachmentService.saveAttachment(attachmentStr, attrType);
		if(aids!=null){
			if (attrs == null){
				attrs = new ArrayList<Attachment>();
			}
			for (Long aid : aids) {
				Attachment at = attachmentDAO.findById(aid);
				attrs.add(at);
			}
		}
		return attrs;
	}
	/***
	 * 保存配置项
	 * 
	 * @param ciDTO
	 *            要保存到数据库的DTO数据值
	 */
	@Transactional
	public void addConfigureItem(CIDTO ciDTO,HardwareDTO hardwareDTO) {
		CI entity = new CI();
		dto2entity(ciDTO, entity);
		// 保存附件
		entity.setCiAttachements(getReleatedAttachment(ciDTO.getAids(), ciDTO.getAttachmentStr(), ModuleUtils.ITSM_CIM));
		
		//折旧率
		if (ciDTO.getDepreciationIsZeroYears() !=null && ciDTO.getDepreciationIsZeroYears() != 0
				&& ciDTO.getArrivalDate() != null) {
			double rate = DepreciationUtil.calculateCIDepreciationRate(ciDTO);
			entity.setCiDepreciation(rate);
		}
		ciDAO.save(entity);
		ciDTO.setCiId(entity.getCiId());
	}

	/***
	 * 更新配置项
	 * 
	 * @param ciDTO
	 *:要更新到数据库的DTO数据值
	 */
	@Transactional
	public void updateConfigureItem(CIDTO ciDTO, HardwareDTO hardwareDTO) {
		CI entity = ciDAO.findById(ciDTO.getCiId());
		compareLogResultsSet(entity, ciDTO);//修改行为
		if (ciDTO.getLocId() != null) {
			EventCategory Loc = eventCategoryDAO.findById(ciDTO.getLocId());
			entity.setLoc(Loc);
		}
		// 历史更新保存
		isupdateConfigureItem(entity,ciDTO.getBeId());
		dto2entity(ciDTO, entity);
		// 保存附件
		List<Attachment> attas = getReleatedAttachment(ciDTO.getAids(), ciDTO.getAttachmentStr(),  ModuleUtils.ITSM_CIM);
		if(entity.getCiAttachements()!=null){
			entity.getCiAttachements().addAll(attas);
		}else{
			entity.setCiAttachements(attas);
		}
		entity.setLastUpdateTime(new Date());

		// 折旧率
		if (ciDTO.getDepreciationIsZeroYears()!=null&&ciDTO.getDepreciationIsZeroYears() != 0
				&& ciDTO.getArrivalDate() != null) {
			double rate = DepreciationUtil.calculateCIDepreciationRate(ciDTO);
			entity.setCiDepreciation(rate);
		}
		ciDTO.setCiId(entity.getCiId());
		ciDAO.merge(entity);

	}
	/**
	 * 配置项修改对比日志
	 * */
	@Transactional
	public void compareLogResultsSet(CI entity,CIDTO ciDTO){
		if (entity != null && ciDTO!=null) {
			StringBuffer msg=new StringBuffer();
			//固定资产编号 
			msg.append(comparativeData("lable.ci.assetNo", entity.getCino(), ciDTO.getCino()));
			
			//msg.append(comparativeData("lable.ci.assetNo", entity.getCino(), ciDTO.getCino()));
			//资产名称 
			msg.append(comparativeData("title.asset.name", entity.getCiname(), ciDTO.getCiname()));
			//产品型号
			msg.append(comparativeData("ci.productType", entity.getModel(), ciDTO.getModel()));
			//序列号
			msg.append(comparativeData("ci.serialNumber", entity.getSerialNumber(), ciDTO.getSerialNumber()));
			//条形码
			msg.append(comparativeData("ci.barcode", entity.getBarcode(), ciDTO.getBarcode()));
			//采购日期
			msg.append(comparativeData("ci.purchaseDate", TimeUtils.format(entity.getBuyDate(),TimeUtils.DATETIME_PATTERN),TimeUtils.format(ciDTO.getBuyDate(),TimeUtils.DATETIME_PATTERN) ));
			//到货日期
			msg.append(comparativeData("ci.arrivalDate", TimeUtils.format(entity.getArrivalDate(),TimeUtils.DATETIME_PATTERN), TimeUtils.format(ciDTO.getArrivalDate(),TimeUtils.DATETIME_PATTERN)));
			//预警日期
			msg.append(comparativeData("ci.warningDate", TimeUtils.format( entity.getWarningDate(),TimeUtils.DATETIME_PATTERN),TimeUtils.format(ciDTO.getWarningDate(),TimeUtils.DATETIME_PATTERN)));
			//采购单号
			msg.append(comparativeData("ci.purchaseNo", entity.getPoNo(), ciDTO.getPoNo()));
			
			//部门
			msg.append(comparativeData("common.dept", entity.getDepartment(), ciDTO.getDepartment()));
			//所属业务实体
			msg.append(comparativeData("label.ci.businessEntity", entity.getWorkNumber(), ciDTO.getWorkNumber()));
			//项目
			msg.append(comparativeData("label.ci.project", entity.getProject(), ciDTO.getProject()));
			//来源单位
			msg.append(comparativeData("ci.productProvider", entity.getSourceUnits(), ciDTO.getSourceUnits()));
			//生命周期
			msg.append(comparativeData("ci.lifeCycle", String.valueOf(entity.getLifeCycle()) ,String.valueOf(ciDTO.getLifeCycle())));
			//保修期
			msg.append(comparativeData("ci.warrantyDate", String.valueOf(entity.getWarranty()), String.valueOf(ciDTO.getWarranty())));
			//报废时间
			msg.append(comparativeData("ci.expiryDate", TimeUtils.format(entity.getWasteTime(),TimeUtils.DATETIME_PATTERN), TimeUtils.format(ciDTO.getWasteTime(),TimeUtils.DATETIME_PATTERN)));
			//借出时间
			msg.append(comparativeData("ci.lendTime", TimeUtils.format(entity.getBorrowedTime(),TimeUtils.DATETIME_PATTERN), TimeUtils.format(ciDTO.getBorrowedTime(),TimeUtils.DATETIME_PATTERN)));
			//预计回收时间
			msg.append(comparativeData("ci.plannedRecycleTime", TimeUtils.format(entity.getExpectedRecoverTime(),TimeUtils.DATETIME_PATTERN), TimeUtils.format(ciDTO.getExpectedRecoverTime(),TimeUtils.DATETIME_PATTERN)));
			//回收时间
			msg.append(comparativeData("ci.recycleTime", TimeUtils.format(entity.getRecoverTime(),TimeUtils.DATETIME_PATTERN), TimeUtils.format(ciDTO.getRecoverTime(),TimeUtils.DATETIME_PATTERN)));
			//使用权限 
			msg.append(comparativeData("ci.usePermission", entity.getUsePermissions(), ciDTO.getUsePermissions()));
			//拥有者
			msg.append(comparativeData("ci.assetOriginalValue", String.valueOf(entity.getAssetsOriginalValue()), String.valueOf(ciDTO.getAssetsOriginalValue())));
			//备注 
			msg.append(comparativeData("common.remark", entity.getCDI(), ciDTO.getCDI()));
			//原使用者
			msg.append(comparativeData("ci.originalUser", entity.getOriginalUser(), ciDTO.getOriginalUser()));
			//使用人
			msg.append(comparativeData("ci.use", entity.getUserName(), ciDTO.getUserName()));
			//拥有者
			msg.append(comparativeData("ci.owner", entity.getOwner(), ciDTO.getOwner()));
			//所属项目
			String oldsystemPlatform=null;
			if(entity.getSystemPlatform()!=null  ){
				oldsystemPlatform=entity.getSystemPlatform().getDname();
			}
			String systemPlatform=null;
			if(MathUtils.isLongEmpty(ciDTO.getSystemPlatformId())){
				DataDictionaryItems system=dataDictionaryItemsDAO.findById(ciDTO.getSystemPlatformId());
				systemPlatform=system.getDname();
			}
			msg.append(comparativeData("label.dc.systemPlatform", oldsystemPlatform, systemPlatform));
			//状态
			String oldstatus=null;
			if(entity.getStatus()!=null  ){
				oldstatus=entity.getStatus().getDname();
			}
			String status=null;
			if(MathUtils.isLongEmpty(ciDTO.getStatusId())){
				DataDictionaryItems statu=dataDictionaryItemsDAO.findById(ciDTO.getStatusId());
				status=statu.getDname();
			}
			msg.append(comparativeData("report.title_Status", oldstatus, status));
			//品牌
			String oldbrand=null;
			if(entity.getBrand()!=null  ){
				oldbrand=entity.getBrand().getDname();
			}
			String brand=null;
			if(MathUtils.isLongEmpty(ciDTO.getBrandId())){
				DataDictionaryItems brands=dataDictionaryItemsDAO.findById(ciDTO.getBrandId());
				brand=brands.getDname();
			}
			msg.append(comparativeData("ci.brands", oldbrand,brand));
			
			//产品提供商
			String oldprovider=null;
			if(entity.getProvider()!=null  ){
				oldprovider=entity.getProvider().getDname();
			}
			String provider=null;
			if(MathUtils.isLongEmpty(ciDTO.getProviderId())){
				DataDictionaryItems providers=dataDictionaryItemsDAO.findById(ciDTO.getProviderId());
				provider=providers.getDname();
			}
			msg.append(comparativeData("label.dc.supplier", oldprovider, provider));
			
			//保存修改行为
			if(msg.toString()!=null && msg.toString()!="" && msg.toString().length()>0){
				BehaviorModification behaviormodification=new BehaviorModification();
				behaviormodification.setActContent(msg.toString().replaceAll("【null】","【】"));
				behaviormodification.setCiId(entity.getCiId());
				behaviormodification.setChangeCode(ciDTO.getChangeCode());
				String userName = appctx.getCurrentLoginName();
				behaviormodification.setUserName(userName);
				behaviorModificationDAO.save(behaviormodification);
				ciDTO.setBeId(behaviormodification.getId());
			}
			
		}
	}
	/**
	 * 比较修改前后扩展属性
	 * @param attrVals
	 * @param OldAttrVals
	 * @return
	 */
	public String getAttrsLogs(Map<String, String> attrVals,Map<String, String> OldAttrVals){
		String msg="";
		LanguageContent lc = LanguageContent.getInstance();
		try {
			for(String key : attrVals.keySet())   {   
				String oldVal=OldAttrVals.get(key);
				oldVal=oldVal==null?"":oldVal;
				String val=attrVals.get(key);
				val=val==null?"":val;
			    if(!val.equals(oldVal)){
			    }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}
	/**
	 * 数据的前后对比
	 * */
	@Transactional
	public String comparativeData(String key,String oldval,String val){
		String result="";
		LanguageContent lc = LanguageContent.getInstance();
		if(StringUtils.hasText(val) && StringUtils.hasText(oldval) && !val.equals(oldval)){
			result=lc.getContent(key)+"："+lc.getContent("lable.By.the")+"【"+oldval+"】"+lc.getContent("lable.Revised.to")+"【"+val+"】<br/>";
		}else if(!StringUtils.hasText(val) && StringUtils.hasText(oldval)){
			result=lc.getContent(key)+"："+lc.getContent("lable.By.the")+"【"+oldval+"】"+lc.getContent("lable.Revised.to")+"【】<br/>";
		}else if(!StringUtils.hasText(oldval) && StringUtils.hasText(val)){
			result=lc.getContent(key)+"："+lc.getContent("lable.By.the")+"【】"+lc.getContent("lable.Revised.to")+"【"+val+"】<br/>";
		}
		return result;
	}
	/**
	 * 查询修改行为
	 * */
    @SuppressWarnings("unchecked")
	public List<BehaviorModificationDTO> findBehaviorModification(CIDTO cidto){
    	PageDTO pg = behaviorModificationDAO.findReleasePager(cidto);
		List<BehaviorModification> list=pg.getData();
		List<BehaviorModificationDTO> listDTO = new ArrayList<BehaviorModificationDTO>(list.size());
		for (BehaviorModification entity : list) {
			BehaviorModificationDTO dto = new BehaviorModificationDTO();
			BehaviorModificationDTO.entity2dto(entity, dto);
			listDTO.add(dto);
		}
		return listDTO;
	}
	/**
	 * 配置项历史
	 * */
	@Transactional
	public void isupdateConfigureItem(CI entity,Long beId) {
		CIDetailDTO ciupdatedto = new CIDetailDTO();
		entity2dto(entity, ciupdatedto);

		CIHistoryUpdate cientity = new CIHistoryUpdate();
		String str = null;
		try {
			str = JSONUtil.serialize(ciupdatedto);

		} catch (JSONException e) {
			LOGGER.error(e);
		}
		String userName = appctx.getCurrentLoginName();
		cientity.setUserName(userName);
		cientity.setUpdateDate(new Date());
		cientity.setCihistoryInfo(str);
		cientity.setRevision(new Date().getTime());
		cientity.setBeId(beId);
		cientity.setCiId(ciupdatedto.getCiId());
		ciHistoryUpdate.save(cientity);
	}

	/**
	 * 配置项历史更新查询
	 * 
	 * @throws ClassNotFoundException
	 * */
	@SuppressWarnings("unchecked")
    public List<CIHistoryUpdateDTO> findCiHistoryUpdate(Long ciid) {

		PageDTO pg = ciHistoryUpdate.findReleasePager(ciid);
		List<CIHistoryUpdate> list=pg.getData();
		List<CIHistoryUpdateDTO> listDTO = new ArrayList<CIHistoryUpdateDTO>(list.size());
		for (CIHistoryUpdate entity : list) {
			CIHistoryUpdateDTO dto = new CIHistoryUpdateDTO();
			CIHistoryUpdateDTO.entity2dto(entity, dto);

			listDTO.add(dto);
		}
		return listDTO;
	}

	/**
	 * 配置项历史更新查询ID
	 * 
	 * @throws ClassNotFoundException
	 * */
	public CIHistoryUpdateDTO findCiHistoryUpdateID(Long id) {
		CIHistoryUpdateDTO dto = new CIHistoryUpdateDTO();
		CIHistoryUpdate entity = ciHistoryUpdate.findById(id);
		CIHistoryUpdateDTO.entity2dto(entity, dto);
		CIDetailDTO ciDTO = null;
		try {
			JSONObject d = JSONObject.fromObject(entity.getCihistoryInfo());
			String[] dateFormats = new String[] {TimeUtils.DATE_PATTERN};
			JSONUtils.getMorpherRegistry().registerMorpher(
					new DateMorpher(dateFormats));
			ciDTO = (CIDetailDTO) JSONObject.toBean(d, CIDetailDTO.class);
		} catch (Exception e) {
			throw new ApplicationException("ERROR_DATA_NO_LONGER_EXISTS\n");
		}
		dto.setCiDTO(ciDTO);
		return dto;
	}

	/**
	 * 删除影响附件
	 * 
	 * @param aid
	 */
	@Transactional
	public void deleteAttachement(Long ciId, Long aid) {
		CI ci = ciDAO.findById(ciId);
		Attachment at = attachmentDAO.findById(aid);
		if (ci.getCiAttachements() != null
				&& ci.getCiAttachements().contains(at)) {
			ci.getCiAttachements().remove(at);
		}
		ciDAO.merge(ci);
	}


	/***
	 * dto to entity
	 * 
	 * @param dto
	 * @param entity
	 */
	private void dto2entity(CIDTO dto, CI entity) {
		try {
			if (dto != null) {
				if (dto.getStatusId() != null) {
					entity.setStatus(dataDictionaryItemsDAO.findById(dto
							.getStatusId()));
				} else {
					entity.setStatus(null);
				}
				if (dto.getSystemPlatformId() != null)
					entity.setSystemPlatform((DataDictionaryItems) this.dataDictionaryItemsDAO
							.findById(dto.getSystemPlatformId()));
				else {
					entity.setSystemPlatform(null);
				}
				if (dto.getBrandId() != null) {
					entity.setBrand(dataDictionaryItemsDAO.findById(dto
							.getBrandId()));
				} else {
					entity.setBrand(null);
				}
				if (dto.getLocId() != null) {
					EventCategory LocId = eventCategoryDAO.findById(dto
							.getLocId());
					entity.setLoc(LocId);
				} else {
					entity.setLoc(null);
				}
				if (dto.getProviderId() != null) {
					entity.setProvider(dataDictionaryItemsDAO.findById(dto
							.getProviderId()));
				} else {
					entity.setProvider(null);
				}
				if (dto.getCategoryNo() != null) {
					CICategory categoryNo = cicategoryDAO.findById(dto
							.getCategoryNo());
					entity.setCategory(categoryNo);
				}else {//集成监控默认分类
					if(StringUtils.hasText(dto.getCategoryName())){
						entity.setCategory(cicategoryDAO.findUniqueBy("cname", dto.getCategoryName()));
					}
					if(entity.getCategory()==null){
						entity.setCategory(cicategoryDAO.findById(1L));
					}
				}
				// 关联服务目录 -已优化
				if (dto.getServiceDirectoryNos() != null) {// 受影响的服务
					List<EventCategory> li = new ArrayList<EventCategory>();
					for (Long lo : dto.getServiceDirectoryNos()) {
						EventCategory ent = eventCategoryDAO.findById(lo);
						li.add(ent);
					}
					entity.setServiceDirectory(li);
				} else
					entity.setServiceDirectory(null);

				entity.setCiId(dto.getCiId());
				CICategory categoryNo = cicategoryDAO.findById(dto.getCategoryNo());
				if(StringUtils.hasText(categoryNo.getCategoryCodeRule())){//判断是否要加上配置项分类编码
					entity.setCino(categoryNo.getCategoryCodeRule()+"-"+dto.getCino());
				}else{
					entity.setCino(dto.getCino());
				}
				entity.setCiname(dto.getCiname());
				entity.setModel(dto.getModel());
				entity.setLifeCycle(dto.getLifeCycle());
				entity.setSerialNumber(dto.getSerialNumber());
				entity.setBarcode(dto.getBarcode());
				entity.setBuyDate(dto.getBuyDate());
				entity.setArrivalDate(dto.getArrivalDate());
				entity.setPoNo(dto.getPoNo());
				entity.setWarningDate(dto.getWarningDate());
				entity.setWarranty(dto.getWarranty());
				entity.setUserName(dto.getUserName());
				entity.setOwner(dto.getOwner());
				entity.setDepartment(dto.getDepartment());
				entity.setCDI(dto.getCDI());
				entity.setWorkNumber(dto.getWorkNumber());
				entity.setProject(dto.getProject());
				entity.setSourceUnits(dto.getSourceUnits());
				entity.setFinanceCorrespond(dto.getFinanceCorrespond());
				entity.setAssetsOriginalValue(dto.getAssetsOriginalValue());
				entity.setWasteTime(dto.getWasteTime());
				entity.setBorrowedTime(dto.getBorrowedTime());
				entity.setOriginalUser(dto.getOriginalUser());
				entity.setRecoverTime(dto.getRecoverTime());
				entity.setIsNewForm(dto.getIsNewForm());
				entity.setExpectedRecoverTime(dto.getExpectedRecoverTime());
				entity.setUsePermissions(dto.getUsePermissions());
				if(dto.getCompanyNo()!=null){
					entity.setCompanyNo(dto.getCompanyNo());
				}else{
					entity.setCompanyNo(1L);
				}
				entity.setLastUpdater(dto.getLastUpdater());
				if(dto.getDepreciationIsZeroYears()!=null){
					entity.setDepreciationIsZeroYears(dto
							.getDepreciationIsZeroYears());
				}
				if(dto.getCiDepreciation()!=null){
					entity.setCiDepreciation(dto.getCiDepreciation());
				}
				entity.setUserNameId(dto.getUserNameId());
				entity.setOwnerId(dto.getOwnerId());
				entity.setOriginalUserId(dto.getOriginalUserId());
			}
		} catch (Exception ex) {
			throw new ApplicationException(ex);
		}
	}

	@Transactional
	private void entity2dto(CI ciEntity, CIDetailDTO ciDto) {
		CIDetailDTO.entity2dto(ciEntity, ciDto);
		if (null != ciEntity.getBrand()) {
			ciDto.setBrandId(ciEntity.getBrand().getDcode());
			ciDto.setBrandName(ciEntity.getBrand().getDname());
		}
		if (null != ciEntity.getLoc()) {
			ciDto.setLocId(ciEntity.getLoc().getEventId());
			EventCategoryDTO categoryDTO=eventCategoryService.findLocationNameById(ciEntity.getLoc().getEventId());
			ciDto.setLoc(categoryDTO.getCategoryLocation());
		}
		if (null != ciEntity.getProvider()) {
			ciDto.setProviderId(ciEntity.getProvider().getDcode());
			ciDto.setProviderName(ciEntity.getProvider().getDname());
		}
		
		if (null != ciEntity.getStatus()) {
			ciDto.setStatusId(ciEntity.getStatus().getDcode());
			ciDto.setStatus(ciEntity.getStatus().getDname());
		}
		if (null != ciEntity.getSystemPlatform()) {
			ciDto.setSystemPlatformId(ciEntity.getSystemPlatform().getDcode());
			ciDto.setSystemPlatform(ciEntity.getSystemPlatform().getDname());
		}
		if (null != ciEntity.getCategory()) {
			ciDto.setCategoryNo(ciEntity.getCategory().getCno());
			ciDto.setCategoryName(ciEntity.getCategory().getCname());
			if (ciEntity.getCategory().getCategoryType() != null
					&& ciEntity.getCategory().getCategoryType() > 0) {
				ciDto.setEavNo(ciEntity.getCategory().getCategoryType());
			}
		}
		List<EventCategory> li = ciEntity.getServiceDirectory();
		List<EventCategoryDTO> listEvent = new ArrayList<EventCategoryDTO>();
		if (li != null && li.size() > 0) {
			for (EventCategory ev : li) {
				EventCategoryDTO evDto = new EventCategoryDTO();
				evDto.setEventId(ev.getEventId());
				evDto.setEventName(ev.getEventName());
				listEvent.add(evDto);
			}

			ciDto.setServiceDirDtos(listEvent);
		}
		// 所属客户
		if (ciEntity.getCompanyNo() != null && ciEntity.getCompanyNo() > 0) {
			Organization org = organizationDAO
					.findById(ciEntity.getCompanyNo());
			if (org != null) {
				ciDto.setCompanyName(org.getOrgName());
				ciDto.setCompanyNo(org.getOrgNo());
			}
		}
		if (ciEntity.getCreateTime() != null) {
			ciDto.setCreateTime(ciEntity.getCreateTime());

		}
		if (ciEntity.getLastUpdateTime() != null) {
			ciDto.setLastUpdateTime(ciEntity.getLastUpdateTime());
		}
		if(ciEntity.getOriginalUserId()!=null && ciEntity.getOriginalUserId()>0){
			User user = userInfoService.findUserById(ciEntity.getOriginalUserId());
			if(user!=null){
				ciDto.setOriginalUser(user.getFullName());
			}
		}
		if(ciEntity.getUserNameId()!=null && ciEntity.getUserNameId()>0){
			User user = userInfoService.findUserById(ciEntity.getUserNameId());
			if(user!=null){
				ciDto.setUserName(user.getFullName());
			}
		}
		if(ciEntity.getOwnerId()!=null && ciEntity.getOwnerId()>0){
			User user = userInfoService.findUserById(ciEntity.getOwnerId());
			if(user!=null){
				ciDto.setOwner(user.getFullName());
			}
		}
	}
	/**
	 * entity to dto
	 * 
	 * @param ciEntity
	 * @param ciDto
	 */
	@Transactional
	private void entity2dto(CI ciEntity, CIDTO ciDto) {
		CIDTO.entity2dto(ciEntity, ciDto);

		if (null != ciEntity.getBrand()) {
			ciDto.setBrandId(ciEntity.getBrand().getDcode());
			ciDto.setBrandName(ciEntity.getBrand().getDname());
		}
		if (null != ciEntity.getLoc()) {
			ciDto.setLocId(ciEntity.getLoc().getEventId());
			ciDto.setLocationName(ciEntity.getLoc().getEventName());
		}
		if (null != ciEntity.getProvider()) {
			ciDto.setProviderId(ciEntity.getProvider().getDcode());
			ciDto.setProviderName(ciEntity.getProvider().getDname());
		}

		if (null != ciEntity.getStatus()) {
			ciDto.setStatusId(ciEntity.getStatus().getDcode());
			ciDto.setStatus(ciEntity.getStatus().getDname());
		}
		if (null != ciEntity.getSystemPlatform()) {
			ciDto.setSystemPlatformId(ciEntity.getSystemPlatform().getDcode());
			ciDto.setSystemPlatformName(ciEntity.getSystemPlatform().getDname());
		}
		if (null != ciEntity.getCategory()) {
			ciDto.setCategoryNo(ciEntity.getCategory().getCno());
			ciDto.setCategoryName(ciEntity.getCategory().getCname());
			if (ciEntity.getCategory().getCategoryType() != null
					&& ciEntity.getCategory().getCategoryType() > 0) {
				ciDto.setEavNo(ciEntity.getCategory().getCategoryType());
			}
		}

		// 所属客户
		if (ciEntity.getCompanyNo() != null && ciEntity.getCompanyNo() > 0) {
			Organization org = organizationDAO
					.findById(ciEntity.getCompanyNo());
			if (org != null) {
				ciDto.setCompanyName(org.getOrgName());
				ciDto.setCompanyNo(org.getOrgNo());
			}
		}
		
		if(ciEntity.getOriginalUserId()!=null && ciEntity.getOriginalUserId()>0){
			User user = userInfoService.findUserById(ciEntity.getOriginalUserId());
			if(user!=null){
				ciDto.setOriginalUser(user.getFullName());
			}
		}
		if(ciEntity.getUserNameId()!=null && ciEntity.getUserNameId()>0){
			User user = userInfoService.findUserById(ciEntity.getUserNameId());
			if(user!=null){
				ciDto.setUserName(user.getFullName());
			}
		}
		if(ciEntity.getOwnerId()!=null && ciEntity.getOwnerId()>0){
			User user = userInfoService.findUserById(ciEntity.getOwnerId());
			if(user!=null){
				ciDto.setOwner(user.getFullName());
			}
		}

	}

	@Transactional
	private void entity2dto(CI ciEntity, CIGridDTO ciDto) {
		
		CIGridDTO.entity2dto(ciEntity, ciDto);

		if (null != ciEntity.getBrand()) {
			ciDto.setBrandId(ciEntity.getBrand().getDcode());
			ciDto.setBrandName(ciEntity.getBrand().getDname());
			ciDto.setBrandNameColor(ciEntity.getBrand().getColor());// 品牌位置
		}
		if (null != ciEntity.getLoc()) {
			ciDto.setLocId(ciEntity.getLoc().getEventId());
			EventCategoryDTO categoryDTO=eventCategoryService.findLocationNameById(ciEntity.getLoc().getEventId());
			ciDto.setLoc(categoryDTO.getCategoryLocation());
		}
		if (null != ciEntity.getProvider()) {
			ciDto.setProviderId(ciEntity.getProvider().getDcode());
			ciDto.setProviderName(ciEntity.getProvider().getDname());
			ciDto.setProviderNameColor(ciEntity.getProvider().getColor());// 产品提供商位置
		}

		if (null != ciEntity.getStatus()) {
			ciDto.setStatusId(ciEntity.getStatus().getDcode());
			ciDto.setStatus(ciEntity.getStatus().getDname());
			ciDto.setStatusColor(ciEntity.getStatus().getColor());// 状态位置
		}
		if (null != ciEntity.getSystemPlatform()) {
			ciDto.setSystemPlatformId(ciEntity.getSystemPlatform().getDcode());
			ciDto.setSystemPlatform(ciEntity.getSystemPlatform().getDname());
			ciDto.setSystemPlatformColor(ciEntity.getSystemPlatform()
					.getColor());// 所属项目位置
		}
		if (null != ciEntity.getCategory()) {
			ciDto.setCategoryNo(ciEntity.getCategory().getCno());
			ciDto.setCategoryName(ciEntity.getCategory().getCname());
			if (ciEntity.getCategory().getCategoryType() != null
					&& ciEntity.getCategory().getCategoryType() > 0) {
				ciDto.setEavNo(ciEntity.getCategory().getCategoryType());
			}
		}
		// 所属客户
		if (ciEntity.getCompanyNo() != null && ciEntity.getCompanyNo() > 0) {
			Organization org = organizationDAO
					.findById(ciEntity.getCompanyNo());
			if (org != null) {
				ciDto.setCompanyName(org.getOrgName());
				ciDto.setCompanyNo(org.getOrgNo());
			}
		}

		// 多少年折旧率为0
		if (ciEntity.getDepreciationIsZeroYears() > 0) {
			ciDto.setDepreciationIsZeroYears(ciEntity
					.getDepreciationIsZeroYears());
			ciDto.setCiDepreciation(ciEntity.getCiDepreciation());
		}

		// IP
		if (ciEntity.getCreateTime() != null) {
			ciDto.setCreateTime(ciEntity.getCreateTime());
		}
		if (ciEntity.getLastUpdateTime() != null) {
			ciDto.setLastUpdateTime(ciEntity.getLastUpdateTime());
		}
		
		if(ciEntity.getOriginalUserId()!=null && ciEntity.getOriginalUserId()>0){
			User user = userInfoService.findUserById(ciEntity.getOriginalUserId());
			if(user!=null){
				ciDto.setOriginalUser(user.getFullName());
			}
		}
		if(ciEntity.getUserNameId()!=null && ciEntity.getUserNameId()>0){
			User user = userInfoService.findUserById(ciEntity.getUserNameId());
			if(user!=null){
				ciDto.setUserName(user.getFullName());
			}
		}
		if(ciEntity.getOwnerId()!=null && ciEntity.getOwnerId()>0){
			User user = userInfoService.findUserById(ciEntity.getOwnerId());
			if(user!=null){
				ciDto.setOwner(user.getFullName());
			}
		}

	}
	
	

	/**
	 * 保存电脑配置项信息
	 * 
	 * @param ciId
	 * @param hardwareDTO
	 * @param softwareDTO
	 */
	@Transactional
	public void saveCiConfigInfo(Long ciId, CiHardwareDTO hardwareDTO,
			CiSoftwareDTO softwareDTO) {
		CI ci = ciDAO.findById(ciId);
		ciDAO.merge(ci);
		
	}



	/**
	 * 获取软件安装信息
	 * 
	 * @param ciId
	 * @return PageDTO
	 */
	@Transactional
	public PageDTO getCiSoftware(Long ciId, int page, int limit) {
		CI ci = ciDAO.findById(ciId);
		PageDTO pages = new PageDTO();
		if (ci.getCiSoftwares() != null && ci.getCiSoftwares().size() > 0) {
			int totalSize = ci.getCiSoftwares().size();
			int start = (page - 1) * limit;
			int end = 0;
			if (totalSize < limit) {
				end = totalSize - 1;
			} else {
				end = limit * page - 1;
				if (end > totalSize) {
					end = totalSize - 1;
				}
			}
			List<CiSoftwareDTO> softwares = new ArrayList<CiSoftwareDTO>();
			for (int i = start; i < ci.getCiSoftwares().size() && i <= end; i++) {
				CiSoftwareDTO dto = new CiSoftwareDTO();
				CiSoftwareDTO.entity2dto(ci.getCiSoftwares().get(i), dto);
				softwares.add(dto);
			}
			pages.setData(softwares);
			pages.setTotalSize(totalSize);
		}
		return pages;
	}
	/**
	 * 根据条件查询导出数据
	 * 
	 * @param dto
	 */
	@Transactional
	public void commonExportCIData(ExportQueryDTO exportQueryDTO) {
		try {
			
		
		CIQueryDTO dto=(CIQueryDTO) exportQueryDTO.getQueryDTO();
		PageDTO pageDTO = null;
		ExportPageDTO exportPageDTO = new ExportPageDTO();
		if(dto!=null){
			if (dto.getFilterId() != null) {
				if (dto.getLoginName() != null) {// 获取登录名
					dto.setCategoryRes(userInfoService.findCategoryNosByLoginName(
							dto.getLoginName(), CONFIGUREITEMCATEGORY_RES));// 设置查看权限
				}
				pageDTO = filterService.findPageByFilter(dto.getFilterId(), 0,
						CSVWriter.EXPORT_SIZE, dto.getWorkNumber(),
						dto.getBarcode());
			} else {
				// 查询分类包含的所有子节点
				if (dto.getCategoryNo() != null) {
					dto.setCategoryNos(categoryAssembly(dto.getCategoryNo()));
				}
				if (dto.getLoginName() != null) {// 获取登录名
					dto.setCategoryRes(userInfoService.findCategoryNosByLoginName(
							dto.getLoginName(), CONFIGUREITEMCATEGORY_RES));// 设置查看权限
				}
				// 所属负责的客户
				if (dto.getCompanyNos() == null) {
					dto.setCompanyNos(itsopUserService.findMyAllCustomer(dto
							.getLoginName()));
				}
				pageDTO = ciDAO.findPager(dto, 0, CSVWriter.EXPORT_SIZE,
						"ciId", "desc");
			}
			exportPageDTO.setData(pageDTO.getData());
			exportPageDTO.setLang(dto.getLang());
			exportPageDTO.setFileName(dto.getFileName());
			exportPageDTO.setEntity(dto.getExportInfo());
			exportPageDTO.setPath(exportQueryDTO.getPath());
		}
		exportData(exportPageDTO);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导出数据处理
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public void exportData(ExportPageDTO p) {
		List<String[]> data = new ArrayList<String[]>();
		LanguageContent lc = LanguageContent.getInstance();
		ExportInfo entity = new ExportInfo();
		if(p!=null){
			data.add(new String[] {
					lc.getContent("label.belongs.client", p.getLang()),
					lc.getContent("label.ci.ciServiceDir", p.getLang()),
					lc.getContent("label.dc.systemPlatform", p.getLang()),
					lc.getContent("title.request.CICategory", p.getLang()),
					lc.getContent("lable.ci.assetNo", p.getLang()),
					lc.getContent("title.asset.name", p.getLang()),
					lc.getContent("ci.productType", p.getLang()),
					lc.getContent("ci.serialNumber", p.getLang()),
					lc.getContent("ci.barcode", p.getLang()),
					lc.getContent("common.state", p.getLang()),
					lc.getContent("ci.brands", p.getLang()),
					lc.getContent("label.dc.supplier", p.getLang()),
					lc.getContent("ci.location", p.getLang()),
					lc.getContent("ci.purchaseDate", p.getLang()),
					lc.getContent("ci.arrivalDate", p.getLang()),
					lc.getContent("ci.warningDate", p.getLang()),
					lc.getContent("ci.purchaseNo", p.getLang()),
					lc.getContent("ci.assetOriginalValue", p.getLang()),
					lc.getContent("ci.FIMapping", p.getLang()),
					lc.getContent("common.dept", p.getLang()),
					lc.getContent("label.role.roleMark", p.getLang()),
					lc.getContent("label.ci.businessEntity", p.getLang()),
					lc.getContent("label.ci.project", p.getLang()),
					lc.getContent("ci.productProvider", p.getLang()),
					lc.getContent("ci.lifeCycle", p.getLang()),
					lc.getContent("ci.warrantyDate", p.getLang()),
					lc.getContent("ci.expiryDate", p.getLang()),
					lc.getContent("ci.lendTime", p.getLang()),
					lc.getContent("ci.plannedRecycleTime", p.getLang()),
					lc.getContent("ci.recycleTime", p.getLang()),
					lc.getContent("ci.usePermission", p.getLang()),
					lc.getContent("ci.originalUser", p.getLang()),
					lc.getContent("ci.use", p.getLang()),
					lc.getContent("ci.owner", p.getLang()),
					lc.getContent("label_hardware", p.getLang()),
					lc.getContent("ci.depreciationIsZeroYears", p.getLang()) + "("
							+ lc.getContent("title.report.year", p.getLang()) + ")",
					lc.getContent("ci.depreciationRate", p.getLang()),
					lc.getContent("common.extendedAttribute", p.getLang()),});
			if (p.getData() != null && p.getData().size() > 0) {
				List<CI> entities = p.getData();
				for (CI ci : entities) {
					convertCiToStringArray(ci, data, p.getLang());
				}
			}
			entity = p.getEntity();
		}
		exportInfoService.exportCommonCSV(data, entity,p.getPath());
	}

	/**
	 * 导出文件
	 */
	public InputStream exportDownLoad(String fileName) {
		InputStream stream = null;
		String filePath = EXPORTPATH + "/" + fileName;
		File file = new File(filePath);
		if (file.exists()) {
			try {
				stream = new FileInputStream(file);
			} catch (Exception e) {
				throw new ApplicationException("ERROE_FILENOTFIND");
			}
		}
		return stream;
	}

	/**
	 * 删除文件方法
	 */
	@Transactional
	public void deleteExportFile() {
		exportInfoDAO.deleteAll();
		delAllFile(EXPORTPATH);
	}

	// 删除文件夹
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			LOGGER.error(e);
		}
	}

	// 删除指定文件夹下所有文件
	// param path 文件夹完整绝对路径
	private static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 导出数据方法
	 */
	@Transactional
	public void exportConfigureItems(CIQueryDTO ciQueryDTO, String sidx,
			String sord) {
		ExportInfo exportInfo = exportInfoService
				.saveExportInfoReturnEntity("ConfigureItem");
		String lang = appctx.getCurrentLanguage()==null?"":appctx.getCurrentLanguage();
		if (ciQueryDTO != null) {
			ciQueryDTO.setLang(lang);
			// 查询分类包含的所有子节点
			if (ciQueryDTO.getCategoryNo() != null) {
				ciQueryDTO.setCategoryNos(categoryAssembly(ciQueryDTO.getCategoryNo()));
			}
			if (ciQueryDTO.getLoginName() != null) {// 获取登录名
				ciQueryDTO.setCategoryRes(userInfoService.findCategoryNosByLoginName(
								ciQueryDTO.getLoginName(),CONFIGUREITEMCATEGORY_RES));// 设置查看权限
			}
			// 所属负责的客户
			if (ciQueryDTO.getCompanyNos() == null) {
				ciQueryDTO.setCompanyNos(itsopUserService
						.findMyAllCustomer(ciQueryDTO.getLoginName()));
			}
			ciQueryDTO.setMqCreator(appctx.getCurrentFullName());
			ciQueryDTO.setExportInfo(exportInfo);
			
			
		}
		ExportQueryDTO exportQueryDTO=new ExportQueryDTO();
		exportQueryDTO.setTenantId(appctx.getCurrentTenantId());
		exportQueryDTO.setQueryDTO(ciQueryDTO);
		exportQueryDTO.setType("ci");
		String path = AppConfigUtils.getInstance().getConfigPathByTenantId(
				"exportFilePath", "exportFile", appctx.getCurrentTenantId());
		exportQueryDTO.setPath(path);
		
		exportMessageProducer.send(exportQueryDTO);
	}

	/**
	 * 根据过滤器导出.
	 * 
	 * @param ciQueryDTO
	 */
	@Transactional
	public void exportConfigureItemsByFilter(CIQueryDTO ciQueryDTO,
			String sidx, String sord) {
		ExportInfo exportInfo = exportInfoService
				.saveExportInfoReturnEntity("ConfigureItem");
		//LanguageContent lc = LanguageContent.getInstance();
		String lang = appctx.getCurrentLanguage();
		ciQueryDTO.setLang(lang);
		if (ciQueryDTO.getFilterId() != null) {
			if (ciQueryDTO.getLoginName() != null) {// 获取登录名
				ciQueryDTO.setCategoryRes(userInfoService.findCategoryNosByLoginName(
								ciQueryDTO.getLoginName(),CONFIGUREITEMCATEGORY_RES));// 设置查看权限
			}
		}
		ciQueryDTO.setMqCreator(userInfoService.getCurrentLoginUser().getFullName());
		ciQueryDTO.setExportInfo(exportInfo);
		
		ExportQueryDTO exportQueryDTO=new ExportQueryDTO();
		exportQueryDTO.setTenantId(appctx.getCurrentTenantId());
		exportQueryDTO.setQueryDTO(ciQueryDTO);
		exportQueryDTO.setType("ci");
		String path = AppConfigUtils.getInstance().getConfigPathByTenantId(
				"exportFilePath", "exportFile", appctx.getCurrentTenantId());
		exportQueryDTO.setPath(path);
		
		exportMessageProducer.send(exportQueryDTO);
	}

	/**
	 *  转成字符数组
	 * @param item
	 * @param data
	 * @param lang
	 */
	@Transactional
	private void convertCiToStringArray(CI item, List<String[]> data, String lang) {
		CIDTO dto = new CIDTO();
		entity2dto(item, dto);
		String lifeCycle = "";
		String warranty = "";
		String mapping = "YES";
		StringBuilder expandProperty = new StringBuilder();
		expandProperty.append("");
		String hardware = "";
		String serviceDir = "";
		String systemPlat = "";
		String ciDepreciation = "0";
		LanguageContent lc = LanguageContent.getInstance();
		if (item.getLifeCycle() != null) {
			lifeCycle = String.valueOf(dto.getLifeCycle());
		}
		if (item.getWarranty() != null) {
			warranty = String.valueOf(item.getWarranty());
		}
		if (!dto.getFinanceCorrespond()) {

			mapping = lc.getContent("common.not", lang);
		}
		if (item.getServiceDirectory() != null) {
			for (EventCategory ev : item.getServiceDirectory()) {
				serviceDir += "," + ev.getEventName();
			}
			if (serviceDir.length() > 0)
				serviceDir = serviceDir.substring(1);
		}
		if (item.getSystemPlatform() != null)
			systemPlat = dto.getSystemPlatformName();
		if (item.getDepreciationIsZeroYears() > 0
				&& item.getArrivalDate() != null
				&& item.getCiDepreciation() <= 0) {
			ciDepreciation = lc
					.getContent("ci.depreciationAlreadyIsZero", lang);
		} else if (item.getDepreciationIsZeroYears() > 0
				&& item.getArrivalDate() != null
				&& item.getCiDepreciation() > 0) {
			if (item.getCiDepreciation() > 100)
				ciDepreciation = "100%";
			else
				ciDepreciation = item.getCiDepreciation() + "%";
		} else
			ciDepreciation = "0";
		String [] datastr={ dto.getCompanyName(), serviceDir, systemPlat,
				dto.getCategoryName(), dto.getCino(), dto.getCiname(),
				dto.getModel(), dto.getSerialNumber(), dto.getBarcode(),
				dto.getStatus(), dto.getBrandName(), dto.getProviderName(),
				dto.getLocationName(), TimeUtils.format(dto.getBuyDate(),TimeUtils.DATETIME_PATTERN),
				TimeUtils.format(dto.getArrivalDate(),TimeUtils.DATETIME_PATTERN),
				TimeUtils.format(dto.getWarningDate(),TimeUtils.DATETIME_PATTERN), dto.getPoNo(),
				dto.getAssetsOriginalValue().toString(), mapping,
				dto.getDepartment(), dto.getCDI(), dto.getWorkNumber(),
				dto.getProject(), dto.getSourceUnits(), lifeCycle, warranty,
				TimeUtils.format(dto.getWasteTime(),TimeUtils.DATETIME_PATTERN),
				TimeUtils.format(dto.getBorrowedTime(),TimeUtils.DATETIME_PATTERN),
				TimeUtils.format(dto.getRecoverTime(),TimeUtils.DATETIME_PATTERN),
				TimeUtils.format(dto.getExpectedRecoverTime(),TimeUtils.DATETIME_PATTERN),
				dto.getUsePermissions(), dto.getOriginalUser(),
				dto.getUserName(), dto.getOwner(),
				hardware, item.getDepreciationIsZeroYears() + "",
				ciDepreciation };
		String[] list=null;
		if(list!=null)
			data.add(list);
		else
			data.add(datastr);
	}
	/**
	 * 硬件信息导出组装
	 * @param hdSimpleDTO
	 * @return
	 */
	@Transactional
	public String hdSimpleDTOToString(HardwareSimpleDTO hdSimpleDTO){
		LanguageContent lc = LanguageContent.getInstance();
		StringBuffer hardware = new StringBuffer();
		if(StringUtils.hasText(hdSimpleDTO.getComputerSystem_name())){//计算机名
			hardware.append(lc.getContent("config.computerName")+"="+hdSimpleDTO.getComputerSystem_name()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getComputerSystem_model())){//计算机型号
			hardware.append(lc.getContent("config_computerSystem_model")+"="+hdSimpleDTO.getComputerSystem_model()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getComputerSystem_domain())){//所在域
			hardware.append(lc.getContent("config_computerSystem_domain")+"="+hdSimpleDTO.getComputerSystem_domain()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getComputerSystem_userName())){//用户名
			hardware.append(lc.getContent("common.Username")+"="+hdSimpleDTO.getComputerSystem_userName()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getOperatingSystem_serialNumber())){//操作系统序列号
			hardware.append(lc.getContent("config.serialNumber")+"="+hdSimpleDTO.getOperatingSystem_serialNumber()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getOperatingSystem_caption())){//系统名称
			hardware.append(lc.getContent("label.logo.sysname")+"="+hdSimpleDTO.getOperatingSystem_caption()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getOperatingSystem_version())){//系统版本
			hardware.append(lc.getContent("config.systemVersion")+"="+hdSimpleDTO.getOperatingSystem_version()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getOperatingSystem_osArchitecture())){//系统框架
			hardware.append(lc.getContent("config_operatingSystem_osArchitecture")+"="+hdSimpleDTO.getOperatingSystem_osArchitecture()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getOperatingSystem_csdVersion())){//补丁版本
			hardware.append(lc.getContent("config_operatingSystem_csdVersion")+"="+hdSimpleDTO.getOperatingSystem_csdVersion()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getOperatingSystem_installDate())){//安装时间
			hardware.append(lc.getContent("config_operatingSystem_installDate")+"="+hdSimpleDTO.getOperatingSystem_installDate()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getOperatingSystem_lastBootUpTime())){//最后启动时间
			hardware.append(lc.getContent("config_operatingSystem_lastBootUpTime")+"="+hdSimpleDTO.getOperatingSystem_lastBootUpTime()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getOperatingSystem_totalVisibleMemorySize())){//总的物理内存
			hardware.append(lc.getContent("config_operatingSystem_totalVisibleMemorySize")+"="+hdSimpleDTO.getOperatingSystem_totalVisibleMemorySize()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getOperatingSystem_totalVirtualMemorySize())){//总的虚拟内存
			hardware.append(lc.getContent("config_operatingSystem_totalVirtualMemorySize")+"="+hdSimpleDTO.getOperatingSystem_totalVirtualMemorySize()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getBaseBoard_name())){//主板名称
			hardware.append(lc.getContent("label.attrGroup.attrGroupName")+"="+hdSimpleDTO.getBaseBoard_name()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getBaseBoard_serialNumber())){//主板序列号
			hardware.append(lc.getContent("ci.serialNumber")+"="+hdSimpleDTO.getBaseBoard_serialNumber()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getBaseBoard_manufacturer())){//主板制造商
			hardware.append(lc.getContent("config.mainboard")+"="+hdSimpleDTO.getBaseBoard_manufacturer()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getBios_serialNumber())){//BIOS序列号
			hardware.append(lc.getContent("config.serialNumber")+"="+hdSimpleDTO.getBios_serialNumber()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getBios_name())){//BIOS名称
			hardware.append(lc.getContent("label.attrGroup.attrGroupName")+"="+hdSimpleDTO.getBios_name()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getBios_manufacturer())){//BIOS制造商
			hardware.append(lc.getContent("config_manufacturer")+"="+hdSimpleDTO.getBios_manufacturer()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getBios_version())){//BIOS版本
			hardware.append(lc.getContent("config_bios_version")+"="+hdSimpleDTO.getBios_version()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getBios_releaseDate())){//BIOS发布时间
			hardware.append(lc.getContent("config_bios_releaseDate")+"="+hdSimpleDTO.getBios_releaseDate()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getProcessor_name())){//CPU名称
			hardware.append(lc.getContent("config_processor_name")+"="+hdSimpleDTO.getProcessor_name()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getProcessor_maxClockSpeed())){//CPU速度
			hardware.append(lc.getContent("config_processor_maxClockSpeed")+"="+hdSimpleDTO.getProcessor_maxClockSpeed()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getProcessor_l2CacheSize())){//二级缓存
			hardware.append(lc.getContent("config_processor_l2CacheSize")+"="+hdSimpleDTO.getProcessor_l2CacheSize()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getProcessor_l3CacheSize())){//三级缓存
			hardware.append(lc.getContent("config_processor_l3CacheSize")+"="+hdSimpleDTO.getProcessor_l3CacheSize()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getProcessor_level())){//CPU分级
			hardware.append(lc.getContent("config_processor_level")+"="+hdSimpleDTO.getProcessor_level()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getNetWork_ip())){//IP
			hardware.append(lc.getContent("label_hostname")+"="+hdSimpleDTO.getNetWork_ip()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getNetWork_mac())){//mac
			hardware.append("MAC="+hdSimpleDTO.getNetWork_mac()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getNetWork_name())){//网卡名称
			hardware.append(lc.getContent("label.attrGroup.attrGroupName")+"="+hdSimpleDTO.getNetWork_name()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getNetWork_dhcp())){//DHCP
			hardware.append("DHCP="+hdSimpleDTO.getNetWork_dhcp()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getNetWork_dhcpServer())){//DHCP服务器
			hardware.append(lc.getContent("config_dhcp_server")+"="+hdSimpleDTO.getNetWork_dhcpServer()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getDesktopMonitor_name())){//监视器名称
			hardware.append(lc.getContent("config_desktopMonitor_name")+"="+hdSimpleDTO.getDesktopMonitor_name()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getDesktopMonitor_screenHeight())){//分辨率
			hardware.append(lc.getContent("config_desktopMonitor_height")+"="+hdSimpleDTO.getDesktopMonitor_screenHeight()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getDesktopMonitor_screenWidth())){//分辨率
			hardware.append(lc.getContent("config_desktopMonitor_width")+"="+hdSimpleDTO.getDesktopMonitor_screenWidth()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getDesktopMonitor_monitorManufacturer())){//制造商
			hardware.append(lc.getContent("config_manufacturer")+"="+hdSimpleDTO.getDesktopMonitor_monitorManufacturer()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getDesktopMonitor_serialNumber())){//序列号
			hardware.append(lc.getContent("ci.serialNumber")+"="+hdSimpleDTO.getDesktopMonitor_serialNumber()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getPointingDevice_Name())){//鼠标名称
			hardware.append(lc.getContent("config_pointingDevice")+"="+hdSimpleDTO.getPointingDevice_Name()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getPointingDevice_description())){//鼠标描述
			hardware.append(lc.getContent("lable.change.checkDesc")+"="+hdSimpleDTO.getPointingDevice_description()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getPointingDevice_serialNumber())){//鼠标序列号
			hardware.append(lc.getContent("ci.serialNumber")+"="+hdSimpleDTO.getPointingDevice_serialNumber()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getPointingDevice_manufacturer())){//鼠标制造商
			hardware.append(lc.getContent("config_manufacturer")+"="+hdSimpleDTO.getPointingDevice_manufacturer()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getKeyboard_Name())){//键盘名称
			hardware.append(lc.getContent("label.role.roleName")+"="+hdSimpleDTO.getKeyboard_Name()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getKeyboard_description())){//键盘描述
			hardware.append(lc.getContent("lable.change.checkDesc")+"="+hdSimpleDTO.getKeyboard_description()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getKeyboard_numberOfFunctionKeys())){//功能键
			hardware.append(lc.getContent("config_keyboard_numberOfFunctionKeys")+"="+hdSimpleDTO.getKeyboard_numberOfFunctionKeys()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getKeyboard_serialNumber())){//键盘序列号
			hardware.append(lc.getContent("ci.serialNumber")+"="+hdSimpleDTO.getKeyboard_serialNumber()+",");
		}
		if(StringUtils.hasText(hdSimpleDTO.getKeyboard_manufacturer())){//键盘制造商
			hardware.append(lc.getContent("config_manufacturer")+"="+hdSimpleDTO.getKeyboard_manufacturer()+",");
		}
		return hardware.toString();
	}
	/**
	 * 从CSV文件进行导入 importFile 导入文件
	 */
	@Transactional
	public String importCI(File importFile, CIDTO ciDto) {
	    return this.importCiDataFromCSV(importFile, ciDto);
	}

	/**
	 * 查询配置项的状态
	 * @param dname
	 * @return String
	 */
	private DataDictionaryItems findDataDictionaryItemsByName(String dname) {
		return dataDictionaryItemsDAO.findUniqueBy("dname", dname);
	}

	/**
	 * 负责客户的数据统计
	 * @return List<CustomerDataCountDTO>
	 */
	@Transactional
	public List<CustomerDataCountDTO> configureItemDataCountByCompanyNo(String loginName) {
		Long[] companyNos = itsopUserService.getRelatedCompanyByLoginName(loginName);
		CIQueryDTO qdto = new CIQueryDTO();
		qdto.setCompanyNos(companyNos);
		//根据分类查看权限
		qdto.setCategoryRes(userInfoService.findCategoryNosByLoginName(loginName,CONFIGUREITEMCATEGORY_RES));
		List<StatResultDTO> statResult = ciDAO.groupStatCiByCompanyNo(qdto);
		List<CustomerDataCountDTO> countsDTO = new ArrayList<CustomerDataCountDTO>();
		
		List<Long> statCompanyNo = new ArrayList<Long>(); 
		for (StatResultDTO srDto : statResult) {
			CustomerDataCountDTO countDTO = new CustomerDataCountDTO();
			// 公司信息
			countDTO.setOrgNo(srDto.getId());
			countDTO.setOrgName(orgDAO.findById(srDto.getId()).getOrgName());
			// 统计数据
			countDTO.setTotal(srDto.getQuantity().intValue());
			statCompanyNo.add(srDto.getId());
			countsDTO.add(countDTO);
		}
		//统计结果为0的返回
//		for(Long companyNo : companyNos){
//			if(!statCompanyNo.contains(companyNo)){
//				CustomerDataCountDTO countDTO = new CustomerDataCountDTO();
//				countDTO.setOrgNo(companyNo);
//				countDTO.setOrgName(orgDAO.findById(companyNo).getOrgName());
//				countDTO.setTotal(0);
//				countsDTO.add(countDTO);
//			}
//		}
		return countsDTO;
	}

	/**
	 * 软件使用许可统计
	 * 
	 * @param softwareName
	 * @return String
	 */
	@Transactional
	public Integer softwareLicenseUseCount(String softwareName) {
		return ciDAO.softwareLicenseUseCount(softwareName);
	}


	/**
	 * 判断配置项生命周期与保修期是否已到期
	 * 
	 * @param arrivalDate
	 * @param lifeCycle
	 * @param warranty
	 * @return String
	 */

	static final String LIFE_CYCLE = "LifeCycle";
	static final String CALC_WARRANTY = "CalcWarranty";
	static final String CALC_WARRANTYS = "-CalcWarranty";
	
	@SuppressWarnings("unused")
	public String calcExpired(Long ciid) {
		CI ci = ciDAO.findById(ciid);
		StringBuffer str = new StringBuffer();
		if (TimeUtils.beForNowMonthDate(ci.getArrivalDate(),
				ci.getLifeCycle())) {
			str.append(LIFE_CYCLE);
		}
		if (TimeUtils.beForNowMonthDate(ci.getArrivalDate(), ci.getWarranty())) {
			if (str == null){
				str.append(CALC_WARRANTY);
			}else{
				str.append(CALC_WARRANTYS);
			}
		}
		return str.toString();
	}

	/**
	 * 根据用户查询所关联的配置项
	 * 
	 * @param ciQueryDTO
	 * @param start
	 * @param limit
	 * @param sidx
	 * @param sord
	 * @return String
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findPageConfigureItemByUser(CIQueryDTO ciQueryDTO,
			int start, int limit, String sidx, String sord) {
		PageDTO page = ciDAO.findPageConfigureItemByUser(null, start, limit,
				sidx, sord, ciQueryDTO);
		if (page != null && page.getData() != null) {
			List<CI> entities = (List<CI>) page.getData();
			List<CIGridDTO> dtos = new ArrayList<CIGridDTO>(entities.size());
			for (CI entity : entities) {
				CIGridDTO dto = new CIGridDTO();
				entity2dto(entity, dto);
				dtos.add(dto);
			}
			page.setData(dtos);
		}

		return page;
	}

	/**
	 * 读取导入文件
	 * 
	 * @param importFile
	 * @return String
	 */
	public List<String> readerWMIFile(File importFile) {
		List<String> returnLine = new ArrayList<String>();
		List<String> inputLine = new ArrayList<String>();
		String fileEncode = FileEncodeUtils.getFileEncode(importFile);
		try {
			inputLine = FileUtils.readLines(importFile,fileEncode);
		} catch (IOException e) {
			LOGGER.error(e);
		}
		for(String line : inputLine){
			if(StringUtils.hasText(line)){
				returnLine.add(line.substring(line.indexOf("{")));
			}
			
		}
		return returnLine;
	}
	/**
	 * JSON转换成Hardware的实体信息进行保存
	 * @param str
	 * @return String
	 */
	/**
	 * long类型时间转换成String类型时间
	 */
	private String longformat(String dateStr) {
	    StringBuffer dateStr1 = new StringBuffer();
		if (dateStr != null && dateStr.length() > 14) {
			String _tempDate = dateStr.substring(0, 15);
			
			dateStr1.append(_tempDate.substring(0, 4)).append("-")
			.append(_tempDate.substring(0, 4)).append("-")
			.append(_tempDate.substring(4, 6)).append("-")
			.append(_tempDate.substring(6, 8)).append(" ")
			.append(_tempDate.substring(8, 10)).append(":")
			.append(_tempDate.substring(10, 12)).append(":")
			.append(_tempDate.substring(12, 14));
		}

		return dateStr1.toString();
	}

	/**
	 * 添加配置项附件
	 */
	@Transactional
	public void saveCIAttachment(Long ciId, String attachmentStr,
			String eventType, Long aid) {
		CI entity = ciDAO.findById(ciId);
		List<Attachment> atts;
		if (entity.getCiAttachements() != null
				&& entity.getCiAttachements().size() > 0) {
			atts = entity.getCiAttachements();
		} else {
			atts = new ArrayList<Attachment>();
		}

		// 保存附件
		if (attachmentStr != null) {
			List<Attachment> attrs = attachmentService.saveAttachment(
					attachmentStr, eventType);
			if (attrs != null && attrs.size() > 0  && atts.size() > 0) {
				HashSet<Attachment> a = new HashSet<Attachment>();
				for (Attachment at : attrs) {
					for (Attachment ats : atts) {
						if(!ats.getAid().equals(at.getAid()))
							a.add(at);
					}
				}
				atts.addAll(a);
			}else
				atts.addAll(attrs);
			
		}
		if (aid != null && aid != 0) {
			Attachment att = attachmentDAO.findById(aid);
			atts.add(att);
		}
		entity.setCiAttachements(atts);
	}

	/**
	 * 报表可链接查询返回值处理
	 * return pageDTO 转换好的数据
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findConfigureItemsByCrosstabCell(KeyTransferDTO ktd, int start, int rows, String sidx, String sord) {
		// 负责的所属客户
		Long[] companyNos = itsopUserService.findMyAllCustomer(appctx.getCurrentLoginName());
		ktd.setEntityClass(ENTITYCLASS);
		ktd.setFilterCategory(FILTERCATEGORY);
		PageDTO pageDTO = linksEventQueryServices.finddynamic(ktd, companyNos, start, rows, sidx, sord);
		List<CI> entities = (List<CI>) pageDTO.getData();
		List<CIGridDTO> dtos = new ArrayList<CIGridDTO>(entities.size());
		for (CI entity : entities) {
			CIGridDTO dto = new CIGridDTO();
			entity2dto(entity, dto);
			dtos.add(dto);
		}
		pageDTO.setData(dtos);
		return pageDTO;
	}
	/**
	 * 更具配置项编号查询 cino,并返回二维码配置项信息
	 * 
	 * */
	@Transactional
	public CIScanDTO findConfigureItemByCIID(Long ciid) {
		CI entity = ciDAO.findById(ciid);
		CIScanDTO ciScanDTO = new CIScanDTO();
		entity2dto(entity, ciScanDTO);
		return ciScanDTO;
	}

	private void entity2dto(CI entity, CIScanDTO ciScanDTO) {
		
		CIDetailDTO ciDetailDTO = findConfigureItemById(entity.getCiId());
		
		
		HardwareDTO hardwareDTOs = findConfigureItenHardware(entity.getCiId());

		ciScanDTO.setCDI(ciDetailDTO.getCDI());
		ciScanDTO.setCiId(ciDetailDTO.getCiId());
		ciScanDTO.setCiname(ciDetailDTO.getCiname());
		ciScanDTO.setCino(ciDetailDTO.getCino());
		ciScanDTO.setSerialNumber(ciDetailDTO.getSerialNumber());
		ciScanDTO.setNetWork_ip(hardwareDTOs.getNetWork_ip());
		ciScanDTO.setNetWork_mac(hardwareDTOs.getNetWork_mac());
		ciScanDTO.setOperatingSystem_caption(hardwareDTOs
				.getOperatingSystem_caption());
		if (ciDetailDTO.getBuyDate() != null)
			ciScanDTO.setBuyDate(TimeUtils.format(ciDetailDTO.getBuyDate(),TimeUtils.DATE_PATTERN));
		ciScanDTO.setOwner(ciDetailDTO.getOwner());
		ciScanDTO.setUserName(ciDetailDTO.getUserName());
		ciScanDTO.setWarningDate(ciDetailDTO.getWarningDate());
		ciScanDTO.setComputerSystem_name(hardwareDTOs.getComputerSystem_name());
		try {
			if (ciDetailDTO.getBuyDate() != null) {
				ciScanDTO.setBuyDate(TimeUtils.format(ciDetailDTO.getBuyDate(),TimeUtils.DATE_PATTERN));
				Calendar cal = Calendar.getInstance();
				//cal.setTime(TimeUtils.parse((ciDetailDTO.getBuyDate().toString()),TimeUtils.DATE_PATTERN));
				cal.setTime( ciDetailDTO.getBuyDate() );
				cal.add(Calendar.MONTH, ciDetailDTO.getWarranty());
				ciScanDTO.setElapsedTime(TimeUtils.format(cal.getTime(),TimeUtils.DATE_PATTERN));
			}
		} catch (Exception e) {
			ciScanDTO.setElapsedTime("");
			LOGGER.error(e);
		}
	}
	/**
	 * 更具配置项编号查询 cino,并返回二维码配置项信息
	 * 
	 * */
	@Transactional
	public CIScanDTO findConfigureItemByCINO(String cino) {
		CI entity = ciDAO.findUniqueBy("cino", cino);
		CIScanDTO ciScanDTO = new CIScanDTO();
		entity2dto(entity, ciScanDTO);
		return ciScanDTO;
	}
	/**
	 * ACL更新
	 * (non-Javadoc)
	 * @see com.wstuo.itsm.cim.service.ICIService#aclUpUpdate()
	 */
	@Deprecated
	public void aclUpUpdate() {
		
	}
	/**
	 * 根据配置项的编号进行查询
	 */
	@Transactional
	public CIDetailDTO findByCieno(String findCino) {
		CIDetailDTO ciDetailDTO = new CIDetailDTO();
		try {
			entity2dto(ciDAO.findBy("cino", findCino).get(0), ciDetailDTO);
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return ciDetailDTO;
	}


	/**
	 * 根据多个id查看信息
	 * 
	 * @param ids
	 * @return String
	 */
	@Transactional
	public List<CIGridDTO> findByIds(Long[] ids) {
		List<CIGridDTO> dtos = new ArrayList<CIGridDTO>();
		for (Long id : ids) {
			if(id!=null){
				CI ci = ciDAO.findById(id);
				if (ci != null) {
					CIGridDTO cidto = new CIGridDTO();
					cidto.setCiId(ci.getCiId());
					cidto.setCino(ci.getCino());
					cidto.setCiname(ci.getCiname());
					if (ci.getCategory() != null) {
						cidto.setCategoryName(ci.getCategory().getCname());
					}
					if (ci.getStatus() != null) {
						cidto.setStatus(ci.getStatus().getDname());
					}
					dtos.add(cidto);
				}
			}
		}
		return dtos;
	}
	/**
	 * 转换成配置项的模版值
	 */
	@Transactional
	public CIDTO convertCiTemplateValue(CIDTO ciDto){
		if(ciDto.getServiceDirectoryNos()!=null && ciDto.getServiceDirectoryNos().length>0){
			   Map<Long,String> map=new HashMap<Long, String>();
				for(Long sNo:ciDto.getServiceDirectoryNos()){
					EventCategory ss=eventCategoryDAO.findById(sNo);
					map.put(ss.getEventId(), ss.getEventName());
				}
				ciDto.setServiceNos(map);
		   }
		return ciDto;
	}
	
	public String importCiDataFromCSV(File importFile, CIDTO cidto){
        int insert = 0,update = 0,failure = 0, total = 0;// 新增// 更新// 失败  // 总数
        StringBuffer importRecode = new StringBuffer("<br>");
        Reader rd = null; CSVReader reader = null;
        LanguageContent lc = LanguageContent.getInstance();
        try {
			String fileEncode = FileEncodeUtils.getFileEncode(importFile);
			rd = new InputStreamReader(new FileInputStream(importFile), fileEncode);// 以字节流方式读取数据
            reader = new CSVReader(rd,0);//构造时，索引从0开始，这样第一次读取就能读取表头
            String[] colName = CIImportUtil.resolveColName( reader.readNext() ,
            		IExportInfoService.STRING_SEPARATOR);//读取表头
            String[] line = null;
            CICategory ciCategory = cicategoryDAO.findCICategoryById( cidto.getCategoryNo() );//读取分类
            while ((line = reader.readNext()) != null) {
            	total ++;boolean isSave = true;
            	Map<String, Object> lineData = CIImportUtil.array2Map(colName, line);
            	String cino = null;
            	if( lineData.get("cino") != null 
            			&& (cino = (String)lineData.get("cino")).length() > 0){
            		CI ci = ciDAO.findUniqueBy("cino", cino); 
            		if( ci == null ){
            			ci = new CI();
            		}else{//编辑
                		isupdateConfigureItem(ci,null);
            			isSave = false;
            		}
            		CIDTO cidto2 = new CIDTO(cidto.getCompanyNo());
            		try {
                    	beanUtil.populate(cidto2, lineData);
                    	dto2entityImport(cidto2, ci, ciCategory);
                    	if( isSave){
                    		ci.setIsNewForm(true);
                    		ciDAO.save(ci);insert++;
                    	}else{
                    		ciDAO.update(ci);update++;
                    	}
					} catch (Exception e) {
						String temp = String.format(lc.getContent("importCI.not.beanError"), total);
						LOGGER.error(temp,e);
	            		importRecode.append(temp);
	            		failure ++;
					}
                	cidto.setCiId(ci.getCiId());
            	}else{
            		importRecode.append(String.format(lc.getContent("importCI.not.cino"), total));
            		failure ++;
            	}
            }
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("导入配置项数据异常" + e);
            failure++;
        } catch (FileNotFoundException e) {
            throw new ApplicationException("ERROR_CSV_FILE_NOT_EXISTS\n" + e, e);
        } catch (IOException e) {
            throw new ApplicationException("ERROR_CSV_FILE_IO\n" + e, e);
        }  catch (Exception e) {
        	LOGGER.error("导入配置项数据异常" + e);//e.printStackTrace();
        	failure++;
        } finally {
            try {
                if (rd != null)
                    rd.close();
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
            	LOGGER.error( e );
            }
        }
		StringBuffer result = new StringBuffer();
        result.append("Total:").append(total).append(",&nbsp;")
        .append("Insert:").append(insert).append(",&nbsp;")
        .append("Update:").append(update).append(",&nbsp;")
        .append("Failure:").append(failure).append(importRecode);
        return result.toString();
	}
	
	private void dto2entityImport(CIDTO dto, CI entity,CICategory ciCategory){
		if( dto != null && entity != null){
			dto.setCiId( entity.getCiId() );
			if ( dto.getStatusName() != null ) {
				entity.setStatus( dataDictionaryItemsDAO.findUniqueByGroupCodeAndName("useStatus",
						dto.getStatusName().trim()) );
			}
			if (dto.getSystemPlatformName() != null){
				entity.setSystemPlatform(dataDictionaryItemsDAO.findUniqueByGroupCodeAndName("systemPlatform",
						dto.getSystemPlatformName().trim()));
			}
			if (dto.getBrandName() != null) {
				entity.setBrand(dataDictionaryItemsDAO.findUniqueByGroupCodeAndName("brand",
						dto.getBrandName().trim()));
			}
			if (dto.getProviderName() != null) {
				entity.setProvider( dataDictionaryItemsDAO.findUniqueByGroupCodeAndName("supplier",
						dto.getProviderName().trim()) );
			}
			if (dto.getLocationName() != null) {
				String locName = dto.locationNameFormat() ;
				entity.setLoc( eventCategoryDAO.findUniqueBy( "pathAlias" , locName ));
			}
			// 关联服务目录 -已优化
			if (dto.getServiceDirectoryNos() != null) {// 受影响的服务
				List<EventCategory> li = new ArrayList<EventCategory>();
				for (Long lo : dto.getServiceDirectoryNos()) {
					EventCategory ent = eventCategoryDAO.findById(lo);
					li.add(ent);
				}
				entity.setServiceDirectory(li);
			} else
				entity.setServiceDirectory(null);
		}
	}
	/**
	 * 从CSV中导出CI数据
	 * @param importFile csv的路径
	 * @param cidto
	 * @return 新增、更新、失败、总条数
	 */
	public String importCiDataFromCSV1(File importFile, CIDTO cidto){
        
        int insert = 0; // 新增
        int update = 0; // 更新
        int failure = 0;// 失败
        int total = 0;  // 总数
        
        Reader rd = null;
        CSVReader reader = null;
        try {
			String fileEncode = FileEncodeUtils.getFileEncode(importFile);
			rd = new InputStreamReader(new FileInputStream(importFile), fileEncode);// 以字节流方式读取数据
            reader = new CSVReader(rd);
            String[] line = null;
            while ((line = reader.readNext()) != null) {
            	total++;
                boolean isAdd = true;   // 是否需要新增
                CI ci = new CI();
                
                if (!StringUtils.hasText(line[0])
                        || !StringUtils.hasText(line[2])
                        || !StringUtils.hasText(line[3])) {
                	
                    throw new ApplicationException("ERROR_CSV_FILE_IO\n");
                }
                
                ci = ciDAO.findUniqueBy("cino", line[2]);
                if (ci != null) {
                	// 历史更新保存
            		isupdateConfigureItem(ci,null);
                    isAdd = false;
                } else {
                    ci = new CI();
                    ci.setCino(line[2]);
                }
                
                CICategory cicategory = cicategoryDAO.findUniqueBy("cname", line[0].toString());
                if(cicategory==null)
                	throw new ApplicationException("ERROR_CSV_FILE_IO\n");
                
                ci.setCategory(cicategory);// 分类
                ci.setSystemPlatform(findDataDictionaryItemsByName(line[1]));// 所属项目
                ci.setCiname(line[3]);// 名称
                ci.setModel(line[4]);// 型号
                ci.setSerialNumber(line[5]);// 序列号
                ci.setBarcode(line[6]);// 条形码
                ci.setStatus(findDataDictionaryItemsByName(line[7]));// 状态
                ci.setBrand(findDataDictionaryItemsByName(line[8]));// 品牌
                ci.setProvider(findDataDictionaryItemsByName(line[9]));// 供应商

                if (!line[10].toString().equals("")) {// 位置
                    EventCategory Loc = eventCategoryDAO.findEventTree(line[10]);
                    ci.setLoc(Loc);
                }
                ci.setBuyDate(TimeUtils.parse(line[11].replace("/", "-"),TimeUtils.DATE_PATTERN));// 购买日期
                ci.setArrivalDate(TimeUtils.parse(line[12].replace("/", "-"),TimeUtils.DATE_PATTERN));// 到货日期
                ci.setWarningDate(TimeUtils.parse(line[13].replace("/", "-"),TimeUtils.DATE_PATTERN));// 预警时间
                ci.setPoNo(line[14]);// 订单号
                // 资产原值
                if (StringUtils.hasText(line[15])) {
                    ci.setAssetsOriginalValue(Double.parseDouble(line[15]));
                }
                
                // 与财务对应
                boolean isFinance = StringUtils.hasText(line[16]) && "YES".equals(line[16]);
                ci.setFinanceCorrespond(isFinance);
                
                // 部门
                ci.setDepartment(line[17]);
                // CDI
                ci.setCDI(line[18]);
                // Work Number
                ci.setWorkNumber(line[19]);
                // Project
                ci.setProject(line[20]);
                // 来源单位
                ci.setSourceUnits(line[21]);
                if (StringUtils.hasText(line[23])
                        && line[22].toString().length() <= 10) {// 生命周期
                    ci.setLifeCycle(Integer.parseInt(line[22]));
                }
                if (StringUtils.hasText(line[23])
                        && line[23].toString().length() < 11) {// 保修期
                    ci.setWarranty(Integer.parseInt(line[23]));
                }
                // 报废时间
                ci.setWasteTime(TimeUtils.parse(line[24],TimeUtils.DATE_PATTERN));
                // 借出时间
                ci.setBorrowedTime(TimeUtils.parse(line[25],TimeUtils.DATE_PATTERN));
                // 预计回收时间
                ci.setExpectedRecoverTime(TimeUtils.parse(line[26],TimeUtils.DATE_PATTERN));
                // 回收时间
                ci.setRecoverTime(TimeUtils.parse(line[27],TimeUtils.DATE_PATTERN));
                // 使用权限
                ci.setUsePermissions(line[28]);
                // 原使用者
                ci.setOriginalUser(line[29]);
                ci.setUserName(line[30]);// 使用人
                ci.setOwner(line[31]);// 拥有者
                
                ci.setCompanyNo(cidto.getCompanyNo());

                if (isAdd) {
                    ciDAO.save(ci);
                    insert++;
                    cidto.setCiId(ci.getCiId());
                } else {
                	ci.setLastUpdateTime(new Date());
                    ciDAO.merge(ci);
                    cidto.setCiId(ci.getCiId());
                    update++;
                }
            }
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("导入配置项数据异常" + e);
            failure++;
        } catch (FileNotFoundException e) {
            throw new ApplicationException("ERROR_CSV_FILE_NOT_EXISTS\n" + e, e);
        } catch (IOException e) {
            throw new ApplicationException("ERROR_CSV_FILE_IO\n" + e, e);
        }  catch (Exception e) {
        	e.printStackTrace();
           LOGGER.error("导入配置项数据异常" + e);
           failure++;
        } finally {
            try {
                if (rd != null)
                    rd.close();
                if (reader != null)
                    reader.close();
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        StringBuffer result = new StringBuffer();
        result.append("Total:").append(total).append(",&nbsp;")
        .append("Insert:").append(insert).append(",&nbsp;")
        .append("Update:").append(update).append(",&nbsp;")
        .append("Failure:").append(failure);
        return result.toString();
    }

	@Transactional
	public BehaviorModificationDTO findBehaviorModificationByid(Long beId) {
		BehaviorModificationDTO dto=null;
		BehaviorModification behaviorModification=behaviorModificationDAO.findById(beId);
		if(behaviorModification!=null){
			dto=new BehaviorModificationDTO();
			BehaviorModificationDTO.entity2dto(behaviorModification, dto);
		}
		
		return dto;
	}

	@Override
	public void saveHardware(CiHardwareDTO hardwareDTO) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public CiHardwareDTO getCiHardware(Long ciId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Integer softwareLicenseTotal(Long ciId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String importWMIFile(File importFile, CIDTO ciDto) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public HardwareDTO findConfigureItenHardware(Long ciId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void addConfigureItemSoftware(Long ciId, Long[] softwareIds) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void deleteConfigureItemSoftware(Long ciId, Long[] softwareIds) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void scanToolUpdate(String configJson) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void scanTooloneUpdate(String ciNo, String configJson) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void deleteSoftAttachement(Long ciId, Long aid) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public CIDetailDTO findByHardwareIp(String hardwareIP) {
		// TODO Auto-generated method stub
		return null;
	}
	
}